from django.shortcuts import render
from teacherCertification.models import TeachPaper,ParperConfig,HistoryParper
from django.core.paginator import Paginator
#引入JsonResponse模块
from django.http import JsonResponse
#导入json模块
import json
#导入uuid模块
import uuid
#导入哈希模块
import hashlib
import os
from django.db.models import Max
from django.conf import settings
# Create your views here.

def query_parper(request):
    data = json.loads(request.body.decode("utf-8"))
    try:
        obj_res = TeachPaper.objects
        for key in data.keys():
            if key == 'pType':
                obj_res = obj_res.filter(pType__icontains=data[key])
            if key == 'trueParper':
                obj_res = obj_res.filter(trueParper__icontains=data[key])
            # if key == 'foods':
            #     obj_res = obj_res.filter(foods__icontains=data[key])
        # obj_res = obj_res.order_by('Pno').values("Pno","pType","courseName","pDescribe","trueParper","KnowPoint1","KnowPoint2","mark")
        obj_res = obj_res.order_by('-Pno').values()
        # 创建Paginator对象
        Count=obj_res.count()
        pageSize=data['pageSize']
        paginator = Paginator(obj_res, pageSize)
        numPage = paginator.num_pages
        page_number = data['page']
        page_obj = paginator.get_page(page_number)
        obj_data = list(page_obj.object_list)
        return JsonResponse({'code': 1, 'data': obj_data, 'pageCout': numPage,'Count':Count})
    except Exception as e:
        return JsonResponse({'code':0,'msg':"查询异常，请联系管理员。\n"+e})


# 添加问题到数据库
def add_questions(request):
    data=json.loads(request.body.decode('utf-8'))

    max_cookno = TeachPaper.objects.aggregate(Max('Pno'))['Pno__max']
    if max_cookno!=None:
        data['Pno']=max_cookno+1
    else:
        data['Pno']=100001
    print(data)
#     添加到数据库
    try:
        obj_question=TeachPaper(Pno=data['Pno'],pType=data['pType'],courseName=data['courseName'],pDescribe=data['pDescribe'],   answer1=data['answer1'],answer2=data['answer2'],answer3=data['answer3'],answer4=data['answer4'],answer5=data['answer5'],Correct=data['Correct'],trueParper=data['trueParper'],KnowPoint1=data['KnowPoint1'],KnowPoint2=data['KnowPoint2'],mark=data['mark'],image=data['image'])
        obj_question.save()
        obj_questions = TeachPaper.objects.all().values()
        # 使用ORM获取所有学生信息
        # 把结果转为list
        questions = list(obj_questions)
        return JsonResponse({'code': 1})
    except Exception as e:
        return  JsonResponse({'code':0,'message':f"添加到数据库异常，请联系管理员！\n{e}"})


def edit_question(request):
    data = json.loads(request.body.decode('utf-8'))
    try:
        # 查找到要修改的学生信息
        obj_parper = TeachPaper.objects.get(Pno=data['Pno'])
        # 依次修改字段
        obj_parper.pType = data['pType']
        obj_parper.courseName = data['courseName']
        obj_parper.pDescribe = data['pDescribe']
        obj_parper.answer1 = data['answer1']
        obj_parper.answer2 = data['answer2']
        obj_parper.answer3 = data['answer3']
        obj_parper.answer4 = data['answer4']
        obj_parper.Correct = data['Correct']
        obj_parper.trueParper = data['trueParper']
        obj_parper.KnowPoint1 = data['KnowPoint1']
        obj_parper.KnowPoint2 = data['KnowPoint2']
        obj_parper.mark = data['mark']
        obj_parper.image = data['image']

        obj_parper.save()
        # 使用ORM获取所有学生信息
        # 把结果转为list
        return JsonResponse({'code': 1, 'data': '操作成功'})
    except Exception as e:
        return JsonResponse({'code': 0, 'message': "修改数据库异常，请联系管理员！"})

def delete_question(request):
    data = json.loads(request.body.decode('utf-8'))
    try:
        # 查找到要修改的学生信息
        obj_question = TeachPaper.objects.get(Pno=data['Pno'])
        # 删除数据
        obj_question.delete()
        # obj_question = TeachPaper.objects.all().values()
        # 使用ORM获取所有学生信息
        # 把结果转为list
        # student = list(obj_students)
        return JsonResponse({'code': 1, 'data': "操作成功"})
    except Exception as e:
        return JsonResponse({'code': 0, 'message': "删除数据库异常，请联系管理员！"})

# 上传文件或图片
def upload_file(request):
#     接受上传文件
    rev_file=request.FILES.get('file_name')
    if not rev_file:
        return  JsonResponse({'code':0,'msg':'图片不存在'})
    #     获得一个唯一的名字：uuid+哈希
    new_name=get_random_str()
    #准备写入的URL
    file_path=os.path.join(settings.MEDIA_ROOT_QUESTION,new_name+os.path.splitext(rev_file.name)[1])
    #写入本地磁盘
    try:
        #xieru
        f=open(file_path,'wb')
        for i in rev_file.chunks():
            f.write(i)
        f.close()
        return JsonResponse({'code':1,'name':new_name+os.path.splitext(rev_file.name)[1]})
    except Exception as e:
        return JsonResponse({'code':0,'msg':str(e)})

# 获取随机数据
def get_random_str():
    #获取UUID随机数
    uuid_val=uuid.uuid4()
    #获取uuid的随机字符串
    uuid_str=str(uuid_val).encode('utf-8')
    #获取MD5实例
    md5=hashlib.md5()
    #拿去md5摘要
    md5.update(uuid_str)
    #返回固定长度的字符串
    return md5.hexdigest()


